package com.gzy.fisherybackend.service.impl;

import static com.gzy.fisherybackend.constant.UserConstant.USER_LOGIN_STATE;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzy.fisherybackend.common.ErrorCode;
import com.gzy.fisherybackend.exception.BusinessException;
import com.gzy.fisherybackend.mapper.UserMapper;
import com.gzy.fisherybackend.model.entity.User;
import com.gzy.fisherybackend.model.vo.LoginUserVO;
import com.gzy.fisherybackend.service.UserService;
import com.gzy.fisherybackend.utils.TokenUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
* @author lenovo
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-03-14 00:02:56
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public long userRegister(String userName, String Password, String checkPassword) {
        // 1. 校验
        if (StrUtil.hasBlank(userName, Password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userName.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名过短");
        }
        if (Password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        if (!Password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        // 2. 检查是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", userName);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 3. 加密
        String encryptPassword = getEncryptPassword(Password);
        // 4. 插入数据
        User user = new User();
        user.setUsername(userName);
        user.setPassword(encryptPassword);
        user.setRole("user");  // 设置默认角色
        String dateStr = DateUtil.now(); // 当前时间字符串，格式：yyyy-MM-dd HH:mm:ss
        Date date = DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss");
        user.setRegisterTime(date); // 格式为yyyy-MM-dd HH:mm:ss
        
        // 4. 保存用户
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return user.getUserID();
    }

    @Override
    public String getEncryptPassword(String Password) {
        // 加个盐值，混淆密码
        final String SALT = "gzy";
        //md5单向加密
        return DigestUtils.md5DigestAsHex((SALT + Password).getBytes());
    }

    @Override
    public LoginUserVO userLogin(String userName, String Password, HttpServletRequest request) {
        // 1. 校验
        if (StrUtil.hasBlank(userName, Password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userName.length() < 3) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (Password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = getEncryptPassword(Password);
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Username", userName);
        queryWrapper.eq("Password", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("用户不存在或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        
        // 更新最后登录时间
        String dateStr = DateUtil.now();
        Date date = DateUtil.parse(dateStr);
        User updateUser = new User();
        updateUser.setUserID(user.getUserID());
        updateUser.setLastLoginTime(date);
        boolean result = this.updateById(updateUser);
        if (!result) {
            log.error("更新最后登录时间失败");
        }
        
        // 查询更新后的完整用户信息
        User newUser = this.getById(user.getUserID());
        
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, newUser);
        
        // 4. 生成token
        String token = TokenUtils.generateToken(userName, encryptPassword);
        
        // 5. 返回脱敏信息
        LoginUserVO loginUserVO = this.getLoginUserVO(newUser);
        loginUserVO.setToken(token);
        return loginUserVO;
    }

    /**
     * 获取脱敏类的用户登录信息
     * @param user
     * @return
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if(user == null){
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtil.copyProperties(user,loginUserVO);
        return loginUserVO;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getUserID() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getUserID();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }


}




